package com.example.camera_apk;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.media.Image;
import android.media.ImageReader;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import androidx.annotation.NonNull;

import java.util.Random;

public class CustomSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
    public HandlerThread mThreadHandler;
    public ImageReader mImageReader;
    Random mRand = new Random();

    public CustomSurfaceView(Context context, AttributeSet attr) {
        super(context,attr);
        getHolder().addCallback(this);
        getHolder().setFormat(PixelFormat.TRANSPARENT);
    }
    @Override
    public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
        setWillNotDraw(false);
        mThreadHandler = new HandlerThread("Camera2");
        mThreadHandler.start();
        mImageReader = ImageReader.newInstance(getWidth(), getHeight(), ImageFormat.JPEG,1);
        mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader imageReader) {
                Image image = imageReader.acquireLatestImage();
                new Handler(mThreadHandler.getLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        //process image
                        image.close();
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                invalidate();
                            }
                        });
                    }
                });
            }
        }, new Handler(mThreadHandler.getLooper()));
    }
    @Override
    protected void onDraw(Canvas canvas) {
        Paint painter = new Paint(Paint.ANTI_ALIAS_FLAG);
        painter.setColor(Color.RED);
        painter.setStyle(Paint.Style.STROKE);
        int x = mRand.nextInt(getWidth()), y = mRand.nextInt(getHeight());
        canvas.drawRect(new Rect(x, y, x+100, y+100), painter);
    }
    @Override
    public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
        surfaceHolder.removeCallback(this);
    }
}
